//
// Created by hyh on 4/27/20.
//

#ifndef VIDEOPLAYER_HYHPLAYER_H
#define VIDEOPLAYER_HYHPLAYER_H

#include <Log.h>
#include <thread>
#include<mutex>
#include <unistd.h>
#include <queue>

using namespace std;

static int refcount = 0;

enum MediaStatus{
    stop,
    start
};


class MediaData{

public:
    uint8_t *data;
    int len;
};

class HyhPlayer{

private:
    JavaVM *javaVM;
    jobject instance;
    ANativeWindow *pANativeWindow;
    const char *filePath;
    const char *video_dst_filename = "/storage/emulated/0/test.mp4";
    const char *audio_dst_filename = "/storage/emulated/0/test.pcm";
    FILE *video_dst_file;
    FILE *audio_dst_file;
    AVCodecContext *videoCodecCtx = NULL;
    AVCodecContext *audioCodecCtx = NULL;
    AVFormatContext *formatCtx = NULL;
    AVStream *videoStream = NULL;
    AVStream *audioStream = NULL;
    int videoStreamIndex = -1;
    int audioStreamIndex = -1;
    AVPacket pkt;
    int width;
    int height;
    AVPixelFormat pixelFormat;
    u_int8_t *video_dst_data[4] = {NULL};
    int video_dst_linesize[4];
    int video_dst_bufsize;
    int video_frame_count = 0;
    int audio_frame_count = 0;
    queue<AVFrame*> videoFrameQueue;
    queue<AVFrame*> audioFrameQueue;
    queue<MediaData*> mediaDataQueue;

    mutex videoMutex;
    mutex audioMutex;
    mutex mediaDataMutex;

    condition_variable audioCv;
    condition_variable videoCv;
    condition_variable mediaDataCv;

    double audio_clock=0;
    int count=0;
    MediaStatus mediaStatus = stop;
    static const int MAX_VIDEO_FRAME = 100;
    static const int MAX_AUDIO_FRAME = 100;

protected:
    int open_codec_context(int *stream_idx,AVCodecContext **dec_ctx, AVFormatContext *fmt_ctx, enum AVMediaType type);
    void decode();
    void playVideo();
    void playAudio();
    AVFrame *getVideoFrame();
    AVFrame *getAudioFrame();

public:

    void open(JavaVM *javaVM, jobject instance, const char *filePath, ANativeWindow *pANativeWindow);
    void putData(uint8_t *data,int len);
    MediaData *getData();
    void close();
    void onComplete();
};

#endif //VIDEOPLAYER_HYHPLAYER_H
